package com.tanhua.controller;

import com.tanhua.interceptor.UserHolder;
import com.tanhua.service.UserInfoService;
import com.tanhua.service.UserService;
import model.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 保存用户信息
     *
     * @param userInfo
     * @param token
     * @return
     */
    @PostMapping("loginReginfo")
    public ResponseEntity loginReginfo(
            @RequestBody UserInfo userInfo,
            @RequestHeader("Authorization") String token) {
        userInfo.setId(UserHolder.getUserId());
        userInfoService.save(userInfo);
        return ResponseEntity.ok(null);
    }

    /**
     * 上传用户头像
     *
     * @param headPhoto
     * @return
     * @throws IOException
     */
    @PostMapping("/loginReginfo/head")
    public ResponseEntity head(MultipartFile headPhoto) throws IOException {
        userInfoService.updateHead(headPhoto, UserHolder.getUserId());
        return ResponseEntity.ok(null);
    }

    /**
     * 登录发送验证码
     *
     * @param map
     * @return
     */
    @PostMapping("login")
    public ResponseEntity login(@RequestBody Map<String, String> map) {
        //获取用户手机号
        String phone = (String) map.get("phone");
        //通过手机号发送短信
        userService.sendMes(phone);
        //返回数据
        return ResponseEntity.ok(null);
    }

    /**
     * 校验登录
     *
     * @param map
     * @return
     */
    @PostMapping("/loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map map) {
        //获取手机号
        String phone = (String) map.get("phone");
        //获取验证码
        String code = (String) map.get("verificationCode");
        //校验登录
        Map resMap = userService.loginVerification(phone, code);
        return ResponseEntity.ok(resMap);
    }
}
